package config

import (
	"fmt"
	"github.com/nick/vdamtools/pkg/loggerv"
	"go.uber.org/zap"
	"gopkg.in/yaml.v3"
	"log"
	"os"
	"path/filepath"
)

// 定义YAML结构
type Config struct {
	Server struct {
		Port     int64  `yaml:"Port"`
		Interval int    `yaml:"Interval"`
		Hostname string `yaml:"Hostname"`
	} `yaml:"Server"`

	Dashboard struct {
		Url string `yaml:"Url"`
	} `yaml:"Dashboard"`
	IotDb struct {
		Host     string `yaml:"Host"`
		Port     string `yaml:"Port"`
		UserName string `yaml:"UserName"`
		Password string `yaml:"Password"`
	} `yaml:"IotDb"`
}

var GlobalConfig Config

func getConfigDir(file string) (string, error) {
	currentDir, err := os.Getwd()
	if err != nil {
		return "", err
	}
	fmt.Printf("currentDir = %s\n", currentDir)
	// Construct paths
	paths := []string{
		filepath.Join(currentDir, file),
		filepath.Join(currentDir, "configs", file),
		filepath.Join(currentDir, "src", file),
	}
	for _, path := range paths {
		// Check if the file exists
		if _, err := os.Stat(path); err == nil {
			// File exists, return the path
			return path, nil
		} else if !os.IsNotExist(err) {
			// Some other error occurred
			return "", err
		}
	}
	return "", err
}

func ReadConfig(file string) {

	dir, _ := getConfigDir(file)
	// 读取YAML文件
	yamlFile, err := os.ReadFile(dir)
	if err != nil {
		log.Fatalf("yaml文件解析error: %v", err)
	}

	// 解析YAML
	var config Config
	err = yaml.Unmarshal(yamlFile, &config)
	if err != nil {
		log.Fatalf("config实体映射error: %v", err)
	}
	GlobalConfig = config
	loggerv.GetLogger().Info("get GlobalConfig", zap.Any("GlobalConfig", GlobalConfig))
}
